	// Password saving/retreiving functions, cleaned up a shitload!

// Should probably write a thing to check if Password Manager is enabled before trying to save/load passwords.

dsPasswords = new Object();

dsPasswords.getPassword = function(url, username) {
	// Returns the password, when given a URL and username to look up.
	// In: URL of site to look up in Password Manager, username of site to look up.
	// Out: Either the password that was found, or a null value if there wasn't one/something blew up.

	var passwordManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
	var logins = passwordManager.findLogins({}, url, null, "Deepest Sender");
	for (var i = 0; i < logins.length; i++) {
		if (logins[i].username == username) {
			return logins[i].password;
			break;
		}
	}
	return null;
}

dsPasswords.savePassword = function(url, username, password) {
	// Saves (or replaces) a password in the Password Manager.
	// In: URL to attach the user/password to, the username to use (you can have different usernames for the same URL,
	// 	and the password to save.
	// Out: True if everything went well, false if it didn't.
	if (!url || !username || !password) {
		return false;
	}
	dsPasswords.deletePassword(url, username);
	var passwordManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
	var nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1", Components.interfaces.nsILoginInfo, "init");
	var loginInfo = new nsLoginInfo(url, null, "Deepest Sender", username, password, "", "");
	passwordManager.addLogin(loginInfo);
	return true;
}

dsPasswords.deletePassword = function(url, username) {
	// Deletes a password from the Password Manager. Should be called if 'Save Password' is disabled, or the account
	//	is deleted.
	// In: URL that the password is attached to, username the password is attached to.
	if (!url || !username) {
		return false;
	}
	var passwordManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
	// Find users for this extension 
	var logins = passwordManager.findLogins({}, url, null, "Deepest Sender");
	for (var i = 0; i < logins.length; i++) {
		if (logins[i].username == username) {
			passwordManager.removeLogin(logins[i]);
			return true;
			break;
		}
	}
	return false;
}

